package com.zsguan.z.zhttp4andr;

import android.text.TextUtils;

import com.zsguan.z.slogger4andr.ZLogger;

import org.apache.http.HttpResponse;
import org.apache.http.ProtocolException;
import org.apache.http.client.RedirectHandler;
import org.apache.http.protocol.HttpContext;

import java.net.URI;

/**
 * Created by chshqiang on 15-9-12.
 * Custom Redirect Handler
 */
public abstract class CustomRedirectHandler implements RedirectHandler {
    private static final int MAX_REDIRECT_COUNT = 15;
    int redirectCount;
    String redirectUrl;
    private String tempRedirectUrl;

    public CustomRedirectHandler() {
    }

    public URI getLocationURI(HttpResponse response, HttpContext context) throws ProtocolException {
        ZLogger.i("CustomRedirectHandler: getLocationURI getRedirectUrl : " + this.tempRedirectUrl);
        return !TextUtils.isEmpty(this.tempRedirectUrl)?URI.create(this.tempRedirectUrl):null;
    }

    public boolean isRedirectRequested(HttpResponse response, HttpContext context) {
        int statusCode = response.getStatusLine().getStatusCode();
        if(statusCode != 301 && statusCode != 302) {
            if(statusCode == 200) {
                this.redirectUrl = this.tempRedirectUrl;
            } else {
                this.onReceivedException();
            }
        } else {
            this.tempRedirectUrl = response.getFirstHeader("Location").getValue();
            if(!TextUtils.isEmpty(this.tempRedirectUrl) && this.redirectCount < 15 && this.shouldRedirectUrl(this.tempRedirectUrl)) {
                ++this.redirectCount;
                return true;
            }
        }

        return false;
    }

    public abstract boolean shouldRedirectUrl(String var1);

    public abstract void onReceivedException();

    public String getRedirectUrl() {
        return this.redirectUrl;
    }

    public int getRedirectCount() {
        return this.redirectCount;
    }

}
